package com.hsgene.order.controller.console;

import com.hsgene.common.util.exception.ErrorCode;
import com.hsgene.common.util.resolver.FromSession;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.result.NullObject;
import com.hsgene.common.util.support.LimitHelper;
import com.hsgene.common.util.support.OrderHelper;
import com.hsgene.common.util.support.Pagination;
import com.hsgene.common.util.web.session.UserInfo;
import com.hsgene.order.condition.OrderRefundCondition;
import com.hsgene.order.dto.console.OrderRefundDetailsDto;
import com.hsgene.order.dto.console.OrderRefundDto;
import com.hsgene.order.dto.console.detail.OrderBaseInfo;
import com.hsgene.order.exception.OrderErrorCode;
import com.hsgene.order.service.ConsoleOrderService;
import com.hsgene.order.service.OrderRefundService;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 订单退款Controller
 *
 * @author wangbing
 * @version 1.0, 2018/11/2
 */
@RestController
@RequestMapping("/v1.0/genetic/testing/refund")
public class OrderRefundController {

    private static Logger LOGGER = LogManager.getLogger(OrderRefundController.class);

    @Resource
    private OrderRefundService orderRefundService;

    @Resource
    private ConsoleOrderService consoleOrderService;

    /**
     * 查询退款申请列表
     *
     * @param orderNo       订单编号
     * @param refundNo      退款编号
     * @param patientName   检测人姓名模糊查询
     * @param beginDataTime 开始时间（yyyy-MM-dd hh:mm:ss）2018-11-28 00:00:00
     * @param endDateTime   截止时间（yyyy-MM-dd hh:mm:ss）2018-11-28 23:59:59
     * @param sortField     排序参数
     * @param sortType      排序顺序
     * @param page          页号
     * @param size          每页大小
     * @return 退款申请列表
     */
    @GetMapping("")
    public ApiResult<Pagination<OrderRefundDto>> queryOrderRefunds(
            @RequestParam(name = "orderNo", required = false) String orderNo,
            @RequestParam(name = "refundNo", required = false) String refundNo,
            @RequestParam(name = "patientName", required = false) String patientName,
            @RequestParam(name = "beginDataTime", required = false) String beginDataTime,
            @RequestParam(name = "endDateTime", required = false) String endDateTime,
            @RequestParam(name = "sortField", defaultValue = "createDateTime") String sortField,
            @RequestParam(name = "sortType", defaultValue = "desc") String sortType,
            @RequestParam("page") int page,
            @RequestParam("size") int size) {
        OrderRefundCondition condition = new OrderRefundCondition();
        condition.setOrderNo(orderNo);
        condition.setRefundNo(refundNo);
        condition.setPatientName(patientName);
        condition.setBeginDataTime(beginDataTime);
        condition.setEndDateTime(endDateTime);
        OrderHelper orderHelper = OrderHelper.create(sortField, sortType);
        LimitHelper limitHelper = LimitHelper.create(page, size);
        return orderRefundService.queryOrderRefunds(condition, orderHelper, limitHelper);
    }

    /**
     * 审核退款申请
     *
     * @param refundId     退款申请id
     * @param access       审核操作：true-通过；false-拒绝【拒绝时原因必填】
     * @param rejectReason 拒绝原因
     * @return 操作结果
     */
    @PutMapping("{refund_id}")
    public ApiResult<NullObject> auditOrderRefund(
            @PathVariable("refund_id") String refundId,
            @RequestParam("access") Boolean access,
            @RequestParam(name = "rejectReason", required = false) String rejectReason,
            @FromSession UserInfo userInfo) {
        return orderRefundService.auditOrderRefund(refundId, access, rejectReason, userInfo.getUserId());
    }

    /**
     * @param orderId 订单id
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.order.dto.console.OrderRefundDetailsDto>
     * @description 退款订单详情
     * @author maodi
     * @createDate 2018/11/27 9:05
     */
    @GetMapping("details/{order_id}")
    public ApiResult<OrderRefundDetailsDto> orderRefundDetails(@PathVariable("order_id") String orderId) {
        try {
            if (StringUtils.isBlank(orderId)) {
                return ApiResult.fail(OrderErrorCode.ORDER_ID_IS_NOT_NULL);
            }
            OrderRefundDetailsDto refundDetailsDto = orderRefundService.queryOrderRefundDetails(orderId);
            //增加详情，调用平台订单详情
            try {
                ApiResult<OrderBaseInfo> apiResult = consoleOrderService.consoleOrderDetail(orderId);
                ErrorCode code = apiResult.getError();
                if (code != null) {
                    return ApiResult.fail(code);
                }
                OrderBaseInfo baseInfo = apiResult.getData();
                if (baseInfo == null) {
                    return ApiResult.fail(OrderErrorCode.GET_PLATFORM_ORDER_DETAILS_IS_ERROR);
                }
                refundDetailsDto.setOrderBaseInfo(baseInfo);
            } catch (Exception e) {
                LOGGER.error(OrderErrorCode.GET_PLATFORM_ORDER_DETAILS_IS_ERROR.getMessage(), e);
                return ApiResult.fail(OrderErrorCode.GET_PLATFORM_ORDER_DETAILS_IS_ERROR);
            }
            return ApiResult.succ(refundDetailsDto);
        } catch (Exception e) {
            LOGGER.error(OrderErrorCode.ORDER_REFUND_DETAILS_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrderErrorCode.ORDER_REFUND_DETAILS_IS_ERROR);
        }
    }

}
